﻿using System;
using System.Collections.Generic;
using System.Text;

namespace System.Data.SugarClient.Soap.V1
{
	internal class V1ModuleAction : V1SessionAction, ISugarSoapModuleAction
	{

		#region Constructors

		internal V1ModuleAction(
			SugarSoapV1.sugarsoap service,
			string session,
			string moduleName)
			: base(service, session) 
		{
			this._moduleName = moduleName;
			this.CheckModuleAvailablilityOrThrow();
		}

		#endregion

		#region Fields

		private readonly string _moduleName;

		#endregion

		#region Properties

		public string Module
		{
			get { return _moduleName; }
		}

		#endregion

		#region Methods

		protected void CheckModuleAvailablilityOrThrow()
		{
			if (!CheckModuleAvailablility())
			{
				throw new SugarException(string.Format("Module {0} is not available", this.Module));
			}
		}

		protected bool CheckModuleAvailablility()
		{
			V1GetAvailableModulesAction action = new V1GetAvailableModulesAction(this.SoapService, this.Session);
			V1GetAvailableModulesActionResult result = action.Execute() as V1GetAvailableModulesActionResult;
			if (!result.Success) throw new SugarException("Can not get module list");
			foreach (string modulename in result.AvailableModules) { if (modulename.Equals(this.Module)) return true; }
			return false;
		}

		#endregion

	}

	internal abstract class V1ModuleActionResult : V1ActionResult, ISugarSoapModuleActionResult
	{

		internal V1ModuleActionResult(
			V1ModuleAction action) : base(action)
		{
		}

		#region ISugarSoapModuleActionResult メンバ

		public new ISugarSoapModuleAction Action
		{
			get { return base.Action as ISugarSoapModuleAction; }
		}

		#endregion

		#region ISugarSoapSessionActionResult メンバ

		ISugarSoapSessionAction ISugarSoapSessionActionResult.Action
		{
			get { return base.Action as ISugarSoapSessionAction; }
		}

		#endregion
	}
}
